# -*- coding: utf-8 -*-
import json

from pyquery import PyQuery
from zc_core.model.items import *
from zc_core.util.common import parse_int, parse_number
from zc_core.util.encrypt_util import md5

from powerchina.matcher import match_catalog_id, match_sku_id, match_brand_id, match_min_buy


def parse_root_catalog(response):
    docs = PyQuery(response.text)
    cat_list = list()
    if docs:
        links = docs('div.menu-content-box ul.tree-ul li.tree-li a')
        for cat1_link in links.items():
            link = cat1_link.attr('href')
            cat1_id = match_catalog_id(link)
            cat1_name = cat1_link.attr('title')
            cat_list.append(build_catalog(cat1_id, cat1_name, 1))

    return cat_list


def parse_sub_catalog(response):
    meta = response.meta
    cat1_id = meta.get('catalog1Id')

    cat_list = list()
    docs = PyQuery(response.text)
    if docs:
        cat2_docs = docs('div.showTable div.catList')
        for cat2_doc in cat2_docs.items():
            cat2_title = cat2_doc('div.cat-title')
            link = cat2_title('div.cat-title-name a')
            cat2_name = link.text()
            cat2_id = md5(cat2_name)
            cat2 = build_catalog(cat2_id, cat2_name, 2, cat1_id)
            cat_list.append(cat2)
            cat3_docs = cat2_doc('div.node-list a')
            for cat3_link in cat3_docs.items():
                cat3_name = cat3_link.attr('title').strip()
                cat3_id = match_catalog_id(cat3_link.attr('href'))
                cat3 = build_catalog(cat3_id, cat3_name, 3, cat2_id)
                cat_list.append(cat3)

    return cat_list


def build_catalog(cat_id, name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = cat_id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat3_id = meta.get('cat3Id')

    sku_list = list()
    jpy = PyQuery(response.text)
    lis = jpy('div#goodsBox ul li')
    for li in lis.items():
        link = li('p.gtitle a')
        sale = li('p.sale span').text().replace('总销量：', '').strip()
        sku = Sku()
        sku['batchNo'] = batch_no
        sku['skuId'] = match_sku_id(link.attr('href'))
        sku['catalog3Id'] = cat3_id
        sku['soldCount'] = parse_number(sale)
        sku_list.append(sku)

    return sku_list


def parse_total_page(response):
    jpy = PyQuery(response.text)
    span = jpy('div.pager div.pages_bar span:contains("每页30条记录")')
    total_page = parse_int(span.prev().text().replace('共', '').replace('页', '')) or 0
    return total_page


def parse_item_data(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    result = ItemData()
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    sold_count = meta.get('soldCount')
    cat3_id = meta.get('catalog3Id')

    spans = jpy('div.crumbs > span')
    cat3_link = spans.eq(3)('a').attr('href')

    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['skuName'] = jpy('div.product-info-detail h1').attr('title')

    price = jpy('div.price div.line-price span.show-price')
    if price:
        result['salePrice'] = parse_number(price.text())
        result['originPrice'] = parse_number(price.text())
    unit = jpy('div.price div.line-price span.orgin')
    if unit:
        result['unit'] = unit.text().strip().replace('/', '').strip()

    images = jpy('div.pic-zoom-big img')
    if images:
        result['skuImg'] = images.attr('src').strip()

    result['soldCount'] = sold_count
    result['catalog3Id'] = match_catalog_id(cat3_link) or cat3_id

    # 品牌
    brand = jpy('div.product-brand a.banner-name')
    if brand:
        result['brandId'] = match_brand_id(brand.attr('href'))
        result['brandName'] = brand.text()

    delivery_day = _get_attr(jpy, '预计出货日')
    if delivery_day:
        result['deliveryDay'] = delivery_day.replace('个工作日', '')
    min_buy = _get_attr(jpy, '最小订货量')
    if min_buy:
        result['minBuy'] = match_min_buy(min_buy)
    sp_sku_id = _get_attr(jpy, '订货号')
    if sp_sku_id:
        result['supplierSkuId'] = sp_sku_id

    return result


def _get_attr(jpy, key):
    attr = jpy(f'div.product-info-detail-other div.attr-title > span.style-description:contains("{key}") + span + span')
    if attr:
        return attr.text()


def parse_price(response):
    meta = response.meta
    try:
        rs = json.loads(response.text)
        if rs:
            result = ItemDataSupply()
            result['batchNo'] = meta.get('batchNo')
            result['skuId'] = meta.get('skuId')
            result['spuId'] = str(rs.get('id'))
            result['salePrice'] = rs.get('sellPrice')
            result['originPrice'] = rs.get('marketPrice')
            sp_sku_id = rs.get('eshopSku', '')
            if sp_sku_id:
                result['supplierSkuId'] = sp_sku_id
            sold_count = rs.get('sale', None)
            if sold_count is not None:
                result['soldCount'] = sold_count
            unit = rs.get('unit', '')
            if unit:
                result['unit'] = unit
            return result
    except Exception as e:
        print('移除代理：e=%s' % e)
